const ws = require("nodejs-websocket");
console.log("开始建立连接...");

const text_produces = {
    "add_user":function(d,c){
        if(!d.name||c.user_name)return;
        d.name = d.name.replace(" ","");
        if(getUsers().includes(d.name)){
            c.sendText(JSON.stringify({type:"error",msg:"该用户已经存在"}));
            return;
        }else if(d.name.length<1||d.name.length>10){
            c.sendText(JSON.stringify({type:"error",msg:"名称范围必须在1~10之间"}));
            return;
        };
        c.user_name = d.name;
        sendAll({type:"global",msg:d.name+"加入了服务器"});
        console.log(d.name+"加入了服务器");
        updateUsers();
    },
    "user":function(d,c){
        if(new Date()-c.last_time<1000){
            c.sendText(JSON.stringify(
                {type:"global",msg:"消息发送过于频繁"}))
        }
        else if(d.msg&&c.user_name){
            c.last_time=new Date();
            sendAll({type:"user",msg:d.msg,name:c.user_name})
        }
    }
}

var server = ws.createServer(function(c){
    c.last_time = new Date();
    c.on("text", function(s){
        let d = JSON.parse(s);
        text_produces[d.type]?text_produces[d.type](d,c):null;
    });
    c.on("close", function(){
        if(c.user_name){
            sendAll({type:"global",msg:c.user_name+"离开了服务器"})
            console.log(c.user_name+"离开了服务器");
            updateUsers();
        }
    });
    c.on("error",function(){
    })
}).listen(8888);

function getAll(f){
    server.connections.forEach((e)=>{
        f(e);
    });
}
function sendAll(m){
    getAll(e=>{
        e.sendText(JSON.stringify(m))
    })
}
function getUsers(){
    let u=[];
    getAll(e=>{
        if(e.user_name){
            u.push(e.user_name);
        }
    });
    return u;
}
function updateUsers(){
    let u = getUsers();
    sendAll({type:"updateuser",users:u,length:u.length});
}